package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.Bean.RoleBean;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.app.service.RoleSetService;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.Menus;
import com.zhongkai.model3.MenusRole;
import com.zhongkai.model3.SetRole;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色管理
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleSetServiceImpl implements RoleSetService {

    @Autowired
    private IBaseDao iBaseDao;

    @Autowired
    private PageQuerDao pageQuerDao;


    /**
     * 角色添加
     *
     * @param role_name   角色名称
     * @param number_list 角色权限
     */
    @Override
    public ZhongkaiResult addRoleSet(String role_name, String number_list) {
        if (StringUtils.isNullOrEmpty(role_name) || StringUtils.isNullOrEmpty(number_list)
                ) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        SetRole setRole;
        setRole = (SetRole) iBaseDao.get("from SetRole sr where sr.name='" + role_name + "'");
        if (setRole != null) {
            return ZhongkaiResult.build(400, "此角色已存在");
        }
        setRole = new SetRole();
        //Long role = pageQuerDao.pageMax(setRole);
        Object object  =  iBaseDao.get("select max(se.id) from SetRole se"); //获取表中id最大值
        // System.out.println(object.toString()+"大哥");
        int aLong = Integer.parseInt(object.toString())+1;
        setRole.setId(aLong);
        setRole.setName(role_name);
        setRole.setRemove("1");
        iBaseDao.save(setRole);



/*            ObjectMapper mapper = new ObjectMapper();
            //MenusBean menusBean = mapper.readValue(json, MenusBean.class);

            //   String jsonString="[{'id':'1'},{'id':'2'}]";
            List<MenusBean> beanList = mapper.readValue(json, new TypeReference<List<MenusBean>>() {
            });*/
        String[] split = number_list.split(",");
        for (String s : split) {
            MenusRole menusRole = new MenusRole();
            menusRole.setId(aLong);
            System.out.println(aLong);
            menusRole.setNumber(Integer.valueOf(s));
            iBaseDao.save(menusRole); //多对多关系保存
            menusRole = null;
        }

    /*        for (MenusBean menusBean : beanList) {


            }*/

        return ZhongkaiResult.ok();


    }


    //导航栏列表
    @Override
    public ZhongkaiResult getMenusList() {

        List<Menus> menus = iBaseDao.find("from Menus");

        return ZhongkaiResult.ok(menus);
    }


    /**
     * 角色修改
     *
     * @param role_id     角色id
     * @param number_list 角色权限
     */
    @Override
    public ZhongkaiResult updateRoleSet(Integer role_id, String number_list) {

        if (role_id == 0 || StringUtils.isNullOrEmpty(number_list)
                ) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        SetRole setRole;

        setRole = (SetRole) iBaseDao.get("from SetRole sr where sr.id='" + role_id + "'");

        if (setRole == null) {
            return ZhongkaiResult.build(400, "角色不存在");
        }

        List<MenusRole> menus = iBaseDao.find("from MenusRole mr where mr.id='" + role_id + "'");

        for (MenusRole menu : menus) {
            iBaseDao.delete(menu);
        }
        String[] split = number_list.split(",");


        for (String s : split) {
            MenusRole menusRole = new MenusRole();
            menusRole.setId(role_id);
            menusRole.setNumber(Integer.valueOf(s));
            iBaseDao.save(menusRole); //多对多关系保存
        }

        return ZhongkaiResult.ok();
    }


    @Override
    public ZhongkaiResult removeRoleSet(Integer role_id) {

        if (role_id == 0
                ) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        SetRole setRole;

        setRole = (SetRole) iBaseDao.get("from SetRole sr where sr.id='" + role_id + "'");

        if (setRole == null) {
            return ZhongkaiResult.build(400, "角色不存在");
        }

        List<MenusRole> menus = iBaseDao.find("from MenusRole mr where mr.id='" + role_id + "'");

        try {
            for (MenusRole menu : menus) {
                iBaseDao.delete(menu);
            }

            iBaseDao.delete(setRole);
            return ZhongkaiResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(400, "删除失败");
        }

    }


    /**
     * 角色列表
     *
     * @param page 页数
     * @param rows 每页数据条数
     */
    @Override
    public ZhongkaiResult listRoleSet(Integer page, Integer rows) {
        if (page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        try {
            PageBean pageBean = new PageBean();
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SetRole.class);
            pageBean.setDetachedCriteria(detachedCriteria);

/*
            Set<MenusRole> roles = new HashSet<>();
            for (MenusRole menusRole : rows1) {
                roles.
            }*/

            pageQuerDao.pageQuery(pageBean);


            List<SetRole> list = pageBean.getRows();
            List<RoleBean> roleBeans = new ArrayList<>();

/*            System.out.println(list.size());
            System.out.println(list);*/
            // Map<SetRole,List<MenusRole>> map = new HashMap<>();
            for (SetRole setRole : list) {
                RoleBean roleBean = new RoleBean();
                List<MenusRole> menus = iBaseDao.find("from MenusRole mr where mr.id='" + setRole.getId() + "'");
                //map.put(setRole,menus);
                roleBean.setRoleId(setRole.getId());
                roleBean.setRoleName(setRole.getName());


                List<RoleBean.Menus_Bean> menus_beans = new ArrayList<>();


                for (MenusRole menu : menus) {
                    RoleBean.Menus_Bean menus_bean = new RoleBean.Menus_Bean();
                    menus_bean.setMenusId(menu.getMenusByNumber().getNumber());
                    menus_bean.setMenusName(menu.getMenusByNumber().getmName());
                    menus_beans.add(menus_bean);
                    menus_bean = null;
                }

                roleBean.setList(menus_beans);

                roleBeans.add(roleBean);

                roleBean = null;
            }

/*
            List<MenusRole> list = pageBean.getRows();

            List<SetRoleBean> setRoleBeanList = new ArrayList<>();


            List<MenusBean> menusBeansList = new ArrayList<>();

            Map<SetRoleBean, List<MenusBean>> map = new HashMap<>();
            for (MenusRole menusRole : list) {


                SetRoleBean setRoleBean1 = new SetRoleBean();
                BeanUtils.copyProperties(menusRole.getSetRoleById(), setRoleBean1); //同属性赋值
                setRoleBeanList.add(setRoleBean1);

*/
/*                for (SetRoleBean setRoleBean : map.keySet()) {

                    if (!setRoleBean.equals(menusRole.getSetRoleById())) {
                        SetRoleBean setRoleBean1 = new SetRoleBean();
                        BeanUtils.copyProperties(menusRole.getSetRoleById(), setRoleBean1); //同属性赋值
                        setRoleBeanList.add(setRoleBean1);
                    }
                }*//*

            }
            Set<SetRoleBean> ts = new HashSet<SetRoleBean>();

            for (SetRoleBean roleBean : setRoleBeanList) {
                ts.add(roleBean);
            }

            for (MenusRole menusRole : list) {
                for (SetRoleBean t : ts) {
                    if (menusRole.getId() == t.getId()) {

                        for (MenusRole role : list) {
                            if (role.getId() == t.getId()) {
                                MenusBean menusBean = new MenusBean();
                                BeanUtils.copyProperties(menusRole.getMenusByNumber(), menusBean); //同属性赋值
                                menusBeansList.add(menusBean);
                            }

                        }

                        map.put(t, menusBeansList);
                        menusBeansList.clear();

                    }
                }
            }

            for (SetRoleBean setRoleBean : map.keySet()) {
                System.out.println(new Gson().toJson(setRoleBean));
                System.out.println(new Gson().toJson(map.get(setRoleBean)));
            }
*/


            pageBean.setRows(roleBeans);
            return ZhongkaiResult.ok(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(405, "查询失败");
        }
    }
}
